//
// Created by admin on 2024/5/15.
//

#include "hal-uart.h"
#include "port_stm32.h"


__attribute__((weak)) void uartEventCallback(void *uart, int event, uint32_t size) {

}

void uartInit(void *uart, uint32_t baud) {
    UART_HandleTypeDef *huart = (UART_HandleTypeDef *) uart;

    __HAL_UART_ENABLE_IT(huart, UART_IT_IDLE);
}

void uartWrite(void *uart, uint8_t *buffer, uint32_t size) {
    HAL_UART_Transmit_DMA((UART_HandleTypeDef *) uart, buffer, size);
}

void uartRead(void *uart, uint8_t *buffer, uint32_t size) {
    HAL_UART_Receive_DMA((UART_HandleTypeDef *) uart, buffer, size);
}

/**
 * @brief   put this function to USARTx_IRQHandler.
 *          stm32fxxx_it.c use method
 *          void USARTx_IRQHandler(void)
 *          {
 *              uartIdleHandler(&huartx, 0x01);
 *          }
 */
__attribute__((weak)) void uartIdleHandler(void *uart, int event) {

    UART_HandleTypeDef *huart = (UART_HandleTypeDef *) uart;
    if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE)) {
        __HAL_UART_CLEAR_IDLEFLAG(huart);
//        HAL_UART_DMAStop(huart);

        uint32_t rxCount = huart->RxXferSize - __HAL_DMA_GET_COUNTER(huart->hdmarx);

        uartEventCallback(uart, 0x01, rxCount);
    }

}

void HAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart) {
    uartEventCallback(huart, 0x02, 0);
}

void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) {
    uartEventCallback(huart, 0x04, 0);
}

void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart) {
    uartEventCallback(huart, 0x08, 0);
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
    uartEventCallback(huart, 0x10, 0);
}

